/**
 * 医学文献搜索服务
 * 负责与后端API通信
 */
import http from '@ohos.net.http'

export class MedicalSearchService {
  private apiUrl: string = 'http://localhost:8000'

  /**
   * 设置API服务器地址
   */
  setApiUrl(url: string): void {
    this.apiUrl = url
  }

  /**
   * 搜索医学文献
   */
  async search(query: string, topK: number = 10): Promise<SearchResult> {
    try {
      // 构建请求
      const requestBody = {
        query: query,
        top_k: topK
      }

      // 发送HTTP请求
      const result = await this.httpRequest(`${this.apiUrl}/search`, 'POST', JSON.stringify(requestBody))
      
      return {
        papers: result.papers.map((paper: PaperData) => ({
          pmid: paper.pmid || '',
          title: paper.title || '',
          shortTitle: this.getShortTitle(paper.title || ''),
          abstract: paper.abstract || '',
          authors: Array.isArray(paper.authors) ? paper.authors.join(', ') : '',
          journal: paper.journal || '',
          publicationDate: paper.publication_date || '',
          keywords: Array.isArray(paper.keywords) ? paper.keywords : [],
          fullTextUrl: paper.full_text_url || '',
          relevanceScore: paper.relevance_score || 0
        })),
        summary: result.summary || '',
        query: result.query || query
      }
    } catch (error) {
      console.error('Search error:', JSON.stringify(error))
      throw error
    }
  }

  /**
   * HTTP请求封装
   */
  private httpRequest(url: string, method: string, extraData?: string): Promise<APIResponse> {
    return new Promise((resolve, reject) => {
      let httpRequest = http.createHttp()
      
      const requestMethod: http.RequestMethod = method === 'POST' ? http.RequestMethod.POST : http.RequestMethod.GET
      
      httpRequest.request(url, {
        method: requestMethod,
        header: {
          'Content-Type': 'application/json'
        },
        extraData: extraData,
        connectTimeout: 60000,
        readTimeout: 60000
      })
      .then((data: http.HttpResponse) => {
        if (data.responseCode === 200) {
          try {
            const result: APIResponse = JSON.parse(data.result.toString())
            resolve(result)
          } catch (error) {
            reject(new Error('Failed to parse response'))
          }
        } else {
          reject(new Error(`HTTP error! status: ${data.responseCode}`))
        }
        httpRequest.destroy()
      })
      .catch((error: Error) => {
        console.error('Request error:', JSON.stringify(error))
        httpRequest.destroy()
        reject(error)
      })
    })
  }

  /**
   * 获取论文短标题（用于标签页显示）
   */
  private getShortTitle(title: string, maxLength: number = 20): string {
    if (title.length <= maxLength) {
      return title
    }
    return title.substring(0, maxLength) + '...'
  }

  /**
   * 检查API服务器健康状态
   */
  async checkHealth(): Promise<boolean> {
    try {
      await this.httpRequest(`${this.apiUrl}/health`, 'GET')
      return true
    } catch (error) {
      return false
    }
  }

  /**
   * 获取系统统计信息
   */
  async getStats(): Promise<SystemStats> {
    try {
      const result: APIResponse = await this.httpRequest(`${this.apiUrl}/stats`, 'GET')
      return {
        papers_in_database: result.papers_in_database || 0,
        index_stats: result.index_stats || { total_vectors: 0, dimension: 0, pmid_count: 0 }
      }
    } catch (error) {
      console.error('Get stats error:', JSON.stringify(error))
      throw error
    }
  }
}

/**
 * 搜索结果接口
 */
export interface SearchResult {
  papers: PaperInfo[]
  summary: string
  query: string
}

/**
 * 论文信息接口
 */
export interface PaperInfo {
  pmid: string
  title: string
  shortTitle: string
  abstract: string
  authors: string
  journal: string
  publicationDate: string
  keywords: string[]
  fullTextUrl: string
  relevanceScore: number
}

/**
 * API返回的论文数据类型
 */
interface PaperData {
  pmid?: string
  title?: string
  abstract?: string
  authors?: string[] | string
  journal?: string
  publication_date?: string
  keywords?: string[]
  full_text_url?: string
  relevance_score?: number
}

/**
 * 系统统计信息
 */
interface SystemStats {
  papers_in_database: number
  index_stats: IndexStats
}

/**
 * 索引统计信息
 */
interface IndexStats {
  total_vectors: number
  dimension: number
  pmid_count: number
}

/**
 * API响应类型
 */
interface APIResponse {
  papers?: PaperData[]
  summary?: string
  query?: string
  papers_in_database?: number
  index_stats?: IndexStats
}